package ciprian.google.parser;

import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import ciprian.google.location_mgr.MapPoint;

/**
 * @author Ciprian Ursu
 * 
 *         Class used to parse a gpx xml file.
 * 
 */

public class GPXXMLParser {
    GPXXMLHandler myHandler = null;

    /**
     * Constructor.
     * 
     * @param filePath
     *            the path of the file to be parsed.
     * 
     */
    public GPXXMLParser(String filePath) {
        try {
            // Create a URL we want to load some xml-data from.
            URL url = new URL(filePath);

            // Get a SAXParser from the SAXPArserFactory.
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

            // Get the XMLReader of the SAXParser we created.
            XMLReader xr = sp.getXMLReader();
            // Create a new ContentHandler and apply it to the XML-Reader
            myHandler = new GPXXMLHandler();
            xr.setContentHandler(myHandler);

            // Parse the xml-data from our URL.
            InputSource is = new InputSource(url.openStream());
            xr.parse(is);
            // Parsing has finished.
        } catch (Exception e) {
            // an Exception was thrown.
            e.printStackTrace();
        }
    }

    public ArrayList<MapPoint> getPoints() {
        if (null != myHandler)
            return myHandler.getPoints();

        return null;
    }
}
